//
//  TestBedViewController.m
//  iPhoneDev02
//
//  Created by smu on 11-7-17.
//  Copyright 2011年 duk. All rights reserved.
//

#import "TestBedViewController.h"
#import <MediaPlayer/MediaPlayer.h>

@implementation TestBedViewController
@synthesize log;
@synthesize savePath;


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    self.navigationController.navigationBar.tintColor = COOKBOOK_PURPLE_COLOR;
    self.navigationItem.rightBarButtonItem = BARBUTTON(@"Get Data", @selector(action:))
    
    // Allow user to pick short or long data //定义导航标签
	UISegmentedControl *seg = [[[UISegmentedControl alloc] initWithItems:[@"Short Long Wrong" componentsSeparatedByString:@" "]] autorelease];
	seg.selectedSegmentIndex = 0;
	seg.segmentedControlStyle = UISegmentedControlStyleBar;
	self.navigationItem.titleView = seg;	
}

- (void) action: (UIBarButtonItem *) bbi
{
    NSNumber *which = [NSNumber numberWithInt:[(UISegmentedControl *)self.navigationItem.titleView selectedSegmentIndex]];
    self.navigationItem.rightBarButtonItem = nil;
    [(UISegmentedControl *)self.navigationItem.titleView setEnabled:NO];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    //使用所谓的convenient method,这个方便接口就是detachNewThreadSelector，
    //这个方法可以直接生成一个线程并启动它，而且无需为线程的清理负责。
    [NSThread detachNewThreadSelector:@selector(getData:) toTarget:self withObject:which];
}

- (void) getData: (NSNumber *) which
{
    //创建了一个副线程，需要专门为他提供自动释放池
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    self.log = [NSMutableString string];
    [self doLog:@"Downloading data now ... \n"];
    NSDate *date = [NSDate date];
    
    NSArray *urlArray = [NSArray arrayWithObjects:SMALL_URL, BIG_URL, FAKE_URL, nil];
    //网络下载，请求部分
    //*****************************************
    NSURL *url = [NSURL URLWithString: [urlArray objectAtIndex:[which intValue]]];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    NSURLResponse *response;
    NSError *error;
    //通过NSURLConnection类同步发出请求
    NSData* result = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
	[self doLog:@"Response expects %d bytes", [response expectedContentLength]];
    [self doLog:@"Response suggested file name: %@", [response suggestedFilename]];
    
    if ([response suggestedFilename]) {
        self.savePath = [DEST_PATH stringByAppendingString:[response suggestedFilename]];
    }
    
    if (!result) {
		[self doLog:@"Error downloading data: %@.", [error localizedDescription]];
    } else if ([response expectedContentLength] < 0) {
        [self doLog:@"Error with download. Carrier redirect?"];
    } else {
        [self doLog:@"Download succeeded."];
		[self doLog:@"Read %d bytes", result.length];
		[self doLog:@"Elapsed time: %0.2f seconds.", -1*[date timeIntervalSinceNow]];
        //***************************
        [result writeToFile:self.savePath atomically:YES];
		[self doLog:@"Data written to file: %@.", self.savePath];
    }
        
    [self performSelectorOnMainThread:@selector(finishedGettingData) withObject:nil waitUntilDone:NO];
    [pool release];
}
     
     
- (void) finishedGettingData
{
    self.navigationItem.rightBarButtonItem = BARBUTTON(@"Get Data", @selector(action:));
    if ([[NSFileManager defaultManager] fileExistsAtPath:self.savePath]) {
        self.navigationItem.leftBarButtonItem = BARBUTTON(@"Play", @selector(startPlayback:))
    }
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	[(UISegmentedControl *)self.navigationItem.titleView setEnabled:YES];
}

//函数的参数个数不确定时
- (void) doLog: (NSString *) formatstring, ...
{
    va_list arglist; //定义一个指向个数可变的参数列表指针
    if (!formatstring) return;
    /*
        使参数列表指针arg_ptr指向函数参数列表中的第一个可选参数，说明：argN是位于第一个可选参数之前的固定参数，
        或者说，最后一个 固定参数；…之前的一个参数），函数参数列表中参数在内存中的顺序与函数声明时的顺序是一致的。
        如果有一va函数的声明是void va_test(char a, char b, char c, …)，则它的固定参数依次是a,b,c，最后一个固定参数argN为c，
        因此就是va_start(arg_ptr, c)
    */
    va_start(arglist, formatstring);
    NSString *outstring = [[[NSString alloc] initWithFormat:formatstring arguments:arglist] autorelease];
    //清空参数列表，并置参数指针arg_ptr无效。
    va_end(arglist);
    [self.log appendString:outstring];
    [self.log appendString:@"\n"];
    //apple不允许程序员在主线程以外的线程中对ui进行操作
    //使用performSelectorOnMainThread进行ui的更新
    [textView performSelectorOnMainThread:@selector(setText:) withObject:self.log waitUntilDone:NO];
}
     
-(void)myMovieFinishedCallback:(NSNotification*)aNotification
{
    MPMoviePlayerController* theMovie=[aNotification object];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie];
    [theMovie release];
}

- (void) startPlayback : (id) sender
{
	MPMoviePlayerController* theMovie=[[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:self.savePath]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMovieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie];
	[theMovie play];
}
     
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}



- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end










